﻿using System.Data;
using System.Drawing;
using System.Windows.Forms;
using DevExpress.Utils;
using DevExpress.XtraBars;
using DevExpress.XtraEditors.Controls;
using E4RPDevExpress10;
using E4RPTools;
using Station.Controls;
using StationCommon;

namespace Station
{
    public partial class MainForm : DevExpress.XtraBars.Ribbon.RibbonForm
    {
        #region Members

        private Controller _controller;

        #endregion

        #region Properties

        public Controller Controller
        {
            set
            {
                _controller = value;
                _controller.OwnerWindow = this;
                workOrderCalendar.Controller = _controller;
                workSheet.Controller = _controller;
                workSheetList.Controller = _controller;
                vehicleList.Controller = _controller;
                mechanicList.Controller = _controller;
                workOrderItemList.Controller = _controller;
                _controller.WorkSheetShow += ControllerWorkSheetShow;
            }
        }

        #endregion

        #region Private Methods

        private bool IsWorkOrderSaved()
        {
            if (xtraTabControl.SelectedTabPage != workSheetXtraTabPage) return false;
            if (_controller == null) return false;
            return _controller.WorkOrder.FolhaObra[0].Id > 0;
        }

        private bool IsAllWorkOrderBilled()
        {
            if (_controller.WorkOrder.ItemFolhaObra.Count == 0)
                return false;
            foreach (var workSheetItem in _controller.WorkOrder.ItemFolhaObra)
            {
                if (workSheetItem.RowState == DataRowState.Deleted)
                    return false;
                if (workSheetItem.Estado != WorkOrderItemState.Facturada.ToString())
                    return false;
            }
            return true;
        }

        private bool AtLeastOneWorkOrderBilled()
        {
            if (_controller.WorkOrder.ItemFolhaObra.Count == 0)
                return false;
            foreach (var workSheetItem in _controller.WorkOrder.ItemFolhaObra)
            {
                if (workSheetItem.RowState == DataRowState.Deleted)
                    continue;
                if (workSheetItem.Estado == WorkOrderItemState.Facturada.ToString())
                    return true;
            }
            return false;
        }
        
        private bool SaveEnable()
        {
            if (xtraTabControl.SelectedTabPage != workSheetXtraTabPage) return false;
            if (_controller == null) return false;
            if (IsAllWorkOrderBilled()) return false;
            return _controller.WorkOrder.FolhaObra[0].Estado != WorkOrderState.Encerrada.ToString();
        }

        private bool BillEnable()
        {
            if (xtraTabControl.SelectedTabPage != workSheetXtraTabPage) return false;
            if (_controller == null) return false;
            if (_controller.WorkOrder.FolhaObra[0].Id <= 0) return false;
            if (IsAllWorkOrderBilled()) return false;
            return _controller.WorkOrder.FolhaObra[0].Estado != WorkOrderState.Encerrada.ToString();
        }

        private bool LockEnable()
        {
            if (xtraTabControl.SelectedTabPage != workSheetXtraTabPage) return false;
            if (_controller == null) return false;
            if (_controller.WorkOrder.FolhaObra[0].Id <= 0) return false;
            if (AtLeastOneWorkOrderBilled()) return false;
            return _controller.WorkOrder.FolhaObra[0].Estado != WorkOrderState.Encerrada.ToString();
        }

        private bool UnLockEnable()
        {
            if (xtraTabControl.SelectedTabPage != workSheetXtraTabPage) return false;
            if (_controller == null) return false;
            if (_controller.WorkOrder.FolhaObra[0].Id <= 0) return false;
            if (AtLeastOneWorkOrderBilled()) return false;
            return _controller.WorkOrder.FolhaObra[0].Estado == WorkOrderState.Encerrada.ToString();
        }

        private void SetControlsStatus()
        {            
            saveWorkSheetBarButtonItem.Enabled = SaveEnable();
            billWorkSheetBarButtonItem.Enabled = BillEnable();
            lockBarButtonItem.Enabled = LockEnable();
            unLockBarButtonItem.Enabled = UnLockEnable();
            printWorkOrderBarButtonItem.Enabled = printPreviewWorkOrderBarButtonItem.Enabled = IsWorkOrderSaved();

            loadLayoutBarButtonItem.Enabled = xtraTabControl.SelectedTabPage == workOrderItemsXtraTabPage;
            saveLayoutBarButtonItem.Enabled = xtraTabControl.SelectedTabPage == workOrderItemsXtraTabPage;
            exportToExcelBarButtonItem.Enabled = xtraTabControl.SelectedTabPage == workOrderItemsXtraTabPage;
            customizeGriColumnsBarButtonItem.Enabled = xtraTabControl.SelectedTabPage == workOrderItemsXtraTabPage;
            printGridBarButtonItem.Enabled = xtraTabControl.SelectedTabPage == workOrderItemsXtraTabPage;
            printPreviewGridBarButtonItem.Enabled = xtraTabControl.SelectedTabPage == workOrderItemsXtraTabPage;
        }

        private void SaveWorkOrder(bool bill)
        {
            workSheet.CloseEditors();
            workSheet.ClearControlErrors();
            Result result = _controller.IsWorkSheetValid(bill);
            if (result.Failed)
            {
                workSheet.SetControlErrors(result);
                if (_controller.WorkOrder.FolhaObra[0].RowError != "")
                    MessageBox.Show(this, _controller.WorkOrder.FolhaObra[0].RowError, "Folha Obra", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            _controller.SaveWorkOrder(this, bill);
        }

        private void SetupReportData()
        {
            relatorioDataSet.Merge(_controller.Reports());
            reportsRepositoryItemLookUpEdit.DataSource = relatorioDataSet.Relatorio;
            reportsRepositoryItemLookUpEdit.DisplayMember = relatorioDataSet.Relatorio.NomeColumn.ToString();
            reportsRepositoryItemLookUpEdit.ValueMember = relatorioDataSet.Relatorio.NomeColumn.ToString();
            reportsRepositoryItemLookUpEdit.Columns.Clear();
            reportsRepositoryItemLookUpEdit.Columns.AddRange(new[] {
                new LookUpColumnInfo("Nome", "Nome", 70, FormatType.None, "", true, HorzAlignment.Near)});
        }

        #endregion Private Methods

        public MainForm()
        {
            InitializeComponent();
            SetControlsStatus();
            printPreviewBarButtonItem.Enabled = false;
            printBarButtonItem.Enabled = false;
            xtraTabControl.SelectedPageChanged += XtraTabControlSelectedPageChanged;
            newWorkSheetBarButtonItem.ItemClick += NewWorkSheetBarButtonItemItemClick;
            saveWorkSheetBarButtonItem.ItemClick += SaveWorkSheetBarButtonItemItemClick;
            billWorkSheetBarButtonItem.ItemClick += BillButtonItemItemClick;
            lockBarButtonItem.ItemClick += LockBarButtonItemItemClick;
            unLockBarButtonItem.ItemClick += UnLockBarButtonItemItemClick;
            printPreviewWorkOrderBarButtonItem.ItemClick += PrintPreviewWorkOrderBarButtonItemItemClick;
            printWorkOrderBarButtonItem.ItemClick += PrintWorkOrderBarButtonItemItemClick;
            // Vehicles
            newVehicleBarButtonItem.ItemClick += NewVehicleBarButtonItemItemClick;
            // Mechanics
            newMechanicBarButtonItem.ItemClick += NewMechanicBarButtonItemItemClick;
            // Reports
            reportsRepositoryItemLookUpEdit.EditValueChanging += ReportsRepositoryItemLookUpEditEditValueChanging;
            printPreviewBarButtonItem.ItemClick += PrintPreviewBarButtonItemItemClick;
            printBarButtonItem.ItemClick += PrintBarButtonItemItemClick;
            // Grid
            loadLayoutBarButtonItem.ItemClick += LoadLayoutBarButtonItemItemClick;
            saveLayoutBarButtonItem.ItemClick += SaveLayoutBarButtonItemItemClick;
            exportToExcelBarButtonItem.ItemClick += ExportToExcelBarButtonItemItemClick;
            customizeGriColumnsBarButtonItem.ItemClick += CustomizeGriColumnsBarButtonItemItemClick;
            printGridBarButtonItem.ItemClick += PrintGridBarButtonItemItemClick;
            printPreviewGridBarButtonItem.ItemClick += PrintPreviewGridBarButtonItemItemClick;
            aboutBarButtonItem.ItemClick += AboutBarButtonItemItemClick;
            exitBarButtonItem.ItemClick += ExitBarButtonItemItemClick;
            Closing += MainFormClosing;
        }               

        void ReportsRepositoryItemLookUpEditEditValueChanging(object sender, ChangingEventArgs e)
        {
            printBarButtonItem.Enabled = e.NewValue != null;
            printPreviewBarButtonItem.Enabled = e.NewValue != null;
        }
        
        protected override void OnLoad(System.EventArgs e)
        {
            base.OnLoad(e);
            SetupReportData();
            _controller.NewWorkSheet();
            _controller.WorkSheetSaved += ControllerWorkSheetSaved;
            xtraTabControl.SelectedTabPage = calendarXtraTabPage;          
        }

        void ControllerWorkSheetSaved(object sender, System.EventArgs e)
        {
            workSheet.UpdateState();
            workSheet.UpdateControl();
            SetControlsStatus();
        }

        void ControllerWorkSheetShow(object sender, System.EventArgs e)
        {
            xtraTabControl.SelectedTabPage = workSheetXtraTabPage;
            workSheet.ClearControlErrors();
            SetControlsStatus();
            workSheetXtraTabPage.Text = _controller.WorkOrder.FolhaObra[0].Id > 0 ? _controller.WorkOrder.FolhaObra[0].Nome : "Nova";
        }

        void XtraTabControlSelectedPageChanged(object sender, DevExpress.XtraTab.TabPageChangedEventArgs e)
        {
            SetControlsStatus();
        }
        
        void NewWorkSheetBarButtonItemItemClick(object sender, ItemClickEventArgs e)
        {
            if (!_controller.ExistsOpenedWorkSheet(this, "Deseja mesmo efectuar nova folha obra?"))
                return;
            xtraTabControl.SelectedTabPage = workSheetsXtraTabPage;
            _controller.NewWorkSheet();            
        }

        void SaveWorkSheetBarButtonItemItemClick(object sender, ItemClickEventArgs e)
        {
            SaveWorkOrder(false);
        }

        void BillButtonItemItemClick(object sender, ItemClickEventArgs e)
        {
            SaveWorkOrder(true);
        }

        void UnLockBarButtonItemItemClick(object sender, ItemClickEventArgs e)
        {
            _controller.UnLockWorkOrder();
        }

        void LockBarButtonItemItemClick(object sender, ItemClickEventArgs e)
        {
            _controller.LockWorkOrder();
        }

        void PrintPreviewWorkOrderBarButtonItemItemClick(object sender, ItemClickEventArgs e)
        {
            _controller.PrintPreviewWorkOrder();
        }

        void PrintWorkOrderBarButtonItemItemClick(object sender, ItemClickEventArgs e)
        {
            _controller.PrintWorkOrder();
        } 

        void NewVehicleBarButtonItemItemClick(object sender, ItemClickEventArgs e)
        {
            xtraTabControl.SelectedTabPage = vehiclesXtraTabPage;
            var control = xtraTabControl.SelectedTabPage.Controls[0];
            ((IVehicleList)control).AddVehicle();
        }

        void NewMechanicBarButtonItemItemClick(object sender, ItemClickEventArgs e)
        {
            xtraTabControl.SelectedTabPage = mechanicsXtraTabPage;
            var control = xtraTabControl.SelectedTabPage.Controls[0];
            ((IMechanicList)control).AddMechanic();
        }

        void PrintPreviewBarButtonItemItemClick(object sender, ItemClickEventArgs e)
        {
            string reportName = reportsBarEditItem.EditValue.ToString();
            RelatorioDataSet.RelatorioRow report = relatorioDataSet.Relatorio.FindByNome(reportName);
            _controller.Print(report.Ficheiro, true);
        }

        void PrintBarButtonItemItemClick(object sender, ItemClickEventArgs e)
        {
            string reportName  = reportsBarEditItem.EditValue.ToString();
            RelatorioDataSet.RelatorioRow report = relatorioDataSet.Relatorio.FindByNome(reportName);
            _controller.Print(report.Ficheiro, false);
        }
        
        void SaveLayoutBarButtonItemItemClick(object sender, ItemClickEventArgs e)
        {
            var control = xtraTabControl.SelectedTabPage.Controls[0];
            var gridView = ((IGridView) control).GridView();
            var listName = ((IGridView) control).ListName;
            var layoutName = _controller.SaveLayout(this, listName, DevExpressHelper.SaveLayoutToXml(gridView));
            if (layoutName != "")
                layoutNameBarStaticItem.Caption = layoutName;
        }

        void LoadLayoutBarButtonItemItemClick(object sender, ItemClickEventArgs e)
        {
            var control = xtraTabControl.SelectedTabPage.Controls[0];
            var gridView = ((IGridView) control).GridView();
            var listName = ((IGridView)control).ListName;
            var layoutName = _controller.LoadLayout(gridView, listName);
            if (layoutName != "")
                layoutNameBarStaticItem.Caption = layoutName;
        }

        void ExportToExcelBarButtonItemItemClick(object sender, ItemClickEventArgs e)
        {
            var control = xtraTabControl.SelectedTabPage.Controls[0];
            DevExpressHelper.ExportToExcel(((IGridView)control).GridView());
        }

        void CustomizeGriColumnsBarButtonItemItemClick(object sender, ItemClickEventArgs e)
        {
            var control = xtraTabControl.SelectedTabPage.Controls[0];
            DevExpressHelper.ColumnsCustomization(((IGridView)control).GridView());
        }

        void PrintGridBarButtonItemItemClick(object sender, ItemClickEventArgs e)
        {
            var control = xtraTabControl.SelectedTabPage.Controls[0];
            var gridView = ((IGridView) control).GridView();
            gridView.GridControl.Print();
            DevExpressHelper.Print(gridView);
        }

        void PrintPreviewGridBarButtonItemItemClick(object sender, ItemClickEventArgs e)
        {
            var control = xtraTabControl.SelectedTabPage.Controls[0];
            var gridView = ((IGridView)control).GridView();
            DevExpressHelper.ShowPrintPreview(gridView);
        }
        
        static void AboutBarButtonItemItemClick(object sender, ItemClickEventArgs e)
        {
            var product = new AboutLabelControl("Station", new Font("Jokerman", 24F, FontStyle.Regular, GraphicsUnit.Point, 0),
                                                Color.ForestGreen, new Point(127, 38));
            var productSymbol = new AboutLabelControl("", new Font("Webdings", 24F, FontStyle.Regular, GraphicsUnit.Point, 2),
                                                      Color.ForestGreen, new Point(242, 38));
            var form = new AboutXtraForm { Version = "1.0.0.0", Product = product, ProductSymbol = productSymbol };
            form.ShowDialog();
        }

        void ExitBarButtonItemItemClick(object sender, ItemClickEventArgs e)
        {
            _controller.CloseConnection();
            Close();
        }

        void MainFormClosing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            _controller.CloseConnection();
        }        
        
    }
}
